import { createRouter, createWebHistory } from 'vue-router'
import vuex from '@/store'

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name:'Login',
    meta: { requiresAuth: false },
    component: () => import( '../views/login/login.vue')
  },
  {
    path: '/home',
    component: () => import('../views/home/home.vue'),
    meta:{requiresAuth: false},
    beforeEnter(to, from, next) {
      if (from.path === '/login') {
        next()
      } else {
        alert('请勿手动修改地址栏，请点返回')
        next('/login')
      }
    }
  },
  // {
  //   path: '/register',
  //   component: () => import( '../views/register/register.vue'),
  //    meta: { requiresAuth: false },
  // },
  {
    path: '/selectExam',
    component: () => import('../views/selectExam/selectExam.vue'),
    meta: { requiresAuth: false },
  },
  {
    path: '/toeflIbt',
    component: () => import('../views/toeflIbt/toeflIbt.vue'),
    meta: { requiresAuth: false },
  },
  {
    path: '/exam',
    component: () => import('../views/exam/exam.vue'),
    meta: { requiresAuth: false },
  },
  {
    path: '/personalCenter',
    component: () => import('../views/personalCenter/personalCenter.vue'),
    meta: { requiresAuth: false },
  },
  //无法匹配路由
  {
    path: '/:pathMatch(.*)*',
    component: () => import('../views/error/error.vue') 
  },
]

// 路由核心对象
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})


//全局路由首位
router.beforeEach((to, from,) => {
  //获取vuex中token
  let token = vuex.state.user.token

  // 如果在登录状态且要去登录界面这是不允许的
  if (token && to.name === 'Login') {
    return false
  }

  // 需要鉴权
  if (to.meta.requiresAuth) {
    if (!token) {
      //如果想去某个界面，但因为鉴权失败需要重新登录，此时可以通过传参方式，将想去的路径携带上
      return {
        path: '/login',
        query: {
          wantTo: to.path
        }
      }
    }
  }

  

  return true
})
export default router
